package team.cdlzz.service;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import team.cdlzz.model.pojo.CodeQuestion;
import team.cdlzz.model.pojo.CodeSubmit;
import team.cdlzz.model.servicePojo.Result;
import team.cdlzz.model.servicePojo.RunData;
import team.cdlzz.util.Base64Util;

import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author zw
 * @date 2022-06-27.
 */
@Service
public class RunService {
    @Value("${run.APP_ID}")
    String APP_ID ;
    @Value("${run.APP_SECRET}")
    String APP_SECRET ;


    /**
     * 传入运行代码的参数 ,后续返回
     * @param code
     * @param input
     * @param type
     * @return
     */
    public Result RUNGetResult(String code,String input,String type) throws IOException {
        String sign = sign(code,input);
        String lang = type;
        // post 请求
        FormBody body = new FormBody.Builder()
                .add("appId", APP_ID)
                .add("sign", sign)
                .add("lang", lang)
                .add("code", URLEncoder.encode(Base64Util.encode(code)))
                .add("input", URLEncoder.encode(Base64Util.encode(input)))
                .build();
        String result = post("http://jsrun.net/api/run/v2", body);
//        System.out.println(result);
        return JSONObject.parseObject(result,Result.class);
    }

    public JSONObject RunResultMap(CodeQuestion codeQuestion, CodeSubmit codeSubmit) {
        System.out.println("校验代码中....");
        String langueType = codeSubmit.getLangueType();
        String answer = codeSubmit.getAnswer();
        try {
            Result  result1 = RUNGetResult(answer, codeQuestion.getExample1Input(), langueType);
//            System.out.println(result1);
            Result result2 = RUNGetResult(answer, codeQuestion.getExample2Input(), langueType);
//            System.out.println(result2);
            codeSubmit.setScore(0);

            RunData runData1 = JSONObject.parseObject(result1.getData(),RunData.class);
            RunData runData2 = JSONObject.parseObject(result2.getData(),RunData.class);

            System.out.println("结果1 "+runData1.getResult());
            System.out.println("结果2" + runData2.getResult());
            if (result1.getError()==0&&runData1.getResult().equals(codeQuestion.getExample1Output())){
                System.out.println("返回数据:" + runData1.getResult()+" == " +"输出数据" + codeQuestion.getExample1Input());
                codeSubmit.setScore(codeSubmit.getScore()+50);
            }
            if (result2.getError()==0&&runData2.getResult().equals(codeQuestion.getExample2Output())) {
                System.out.println("返回数据:" + runData2.getResult()+" == " +"输出数据" + codeQuestion.getExample2Input());
                codeSubmit.setScore(codeSubmit.getScore()+50);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("result1",result1);
            jsonObject.put("result2",result2);
            jsonObject.put("submit",codeSubmit);
            return jsonObject;
        } catch (IOException e) {
//            throw new RuntimeException(e);
            e.printStackTrace();
        }
        return null;
    }

     String sign(String code,String input) {
        return md5(code + input + APP_SECRET);
    }

    String md5(String str) {
        /**
         * Spring 中建议直接使用 DigestUtils.md5DigestAsHex() 计算md5值
         */
        try {
            byte[] secretBytes = null;
            secretBytes = MessageDigest.getInstance("md5").digest(str.getBytes());
            String s = DigestUtils.md5DigestAsHex(str.getBytes());
            return s;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
    }

     String post(String url, RequestBody body) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).post(body).build();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

